﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel;
using System.Text;

namespace Tradex.Connectivity {

    /// <summary>
    /// The ConnectorControlApiFacory is a factory for properly configured access channels
    /// to the ConnectorControl.
    /// </summary>
    public sealed class ConnectorApiFactory : IDisposable {

        /// <summary>
        /// The Factory for an IConnectorApi implementation of a named connector.
        /// </summary>
        /// <param name="connector"></param>
        public ConnectorApiFactory(string connector) {
            _Factory = new ChannelFactory<IConnectorApi>(
                new NetNamedPipeBinding(NetNamedPipeSecurityMode.None) { MaxReceivedMessageSize = 65536 * 64 },
                new EndpointAddress(ConnectorApiHost.GetConnectorControlUrl (connector))
            );
        }

        ChannelFactory<IConnectorApi> _Factory;

        /// <summary>
        /// Returns a configured channel to the connector.
        /// </summary>
        /// <returns></returns>
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")]
        public IConnectorApi GetChannel() {
            return _Factory.CreateChannel();
        }

        /// <inheritdoc />
        public void Dispose() {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        void Dispose(bool disposing) {
            if (disposing) {
                if (_Factory != null) {
                    ((IDisposable)_Factory).Dispose();
                    _Factory = null;
                }
            }
        }
    }

}
